class DocumentoFiscal < ActiveRecord::Base

  named_scope :nota, :conditions => "cnpj IS NOT NULL"

  has_many :investimentos, :dependent => :destroy

  validates_presence_of     :numero, :data, :razao_social
  validates_cnpj_of         :cnpj,   :allow_blank => true
  validates_numericality_of :valor,  :greater_than => 0

  # Helpers
  def cnpj=(value)
    self[:cnpj] = value.try :gsub, /\D/, ""
  end

  def importacao?
    cnpj.blank?
  end

  def tipo
    importacao? ? "DI" : "NF"
  end

  def caracterizacao
    Caracterizacao.first(:joins => {:investimentos => :documento_fiscal},
                         :conditions => {'investimentos.documento_fiscal_id' => self.id})
  end

end
